package com.rmdjzz.slmmn.controller.admin.songManagement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rmdjzz.slmmn.pojo.base.Comment;
import com.rmdjzz.slmmn.pojo.base.Singer;
import com.rmdjzz.slmmn.pojo.base.Song;
import com.rmdjzz.slmmn.pojo.result.Result;
import com.rmdjzz.slmmn.pojo.vo.*;
import com.rmdjzz.slmmn.service.SingerService;
import com.rmdjzz.slmmn.service.SongService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @作者 张绍鑫
 * @创建时间 2023/5/30
 */
@Controller
@Api(tags = "歌曲管理api文档")
@RequestMapping("/admin")
@Slf4j
public class SongController {
    @Autowired
    private SongService songService;
    @Autowired
    private SingerService singerService;
    @PostMapping("/songIns")
    @ResponseBody
    @ApiOperation("添加歌曲 需要选择songImg,songName,songTime,singerId")
    public Result songIns(Song song, MultipartFile fileSongImg,MultipartFile fileSongMP3){
        Integer singerId = song.getSingerId();

        Singer byId =singerService.getById(singerId);
        log.info("song:"+song);

        if (byId == null) throw new RuntimeException("该歌手不存在");
        System.out.println(song.getSongName());

        song.setHeat(0);
        song.setNum(0);
        //歌曲海报设置规则：文件名+uuid+png---存放在虚拟路径song文件下
        //生成uuid
        String s = UUID.randomUUID().toString();
        try {
            //获取输入流j
            InputStream inputStream = fileSongImg.getInputStream();
            //获取输出流
            //准备待写入的文件h
            String url="C:\\slmmn\\song\\"+fileSongImg.getName()+s+".png";
            writeFile(inputStream, url);
            //设置歌曲类的海报存放路径
            song.setSongImg("/song/"+fileSongImg.getName()+s+".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //歌曲设置规则：文件名+uuid+png---存放在虚拟路径song文件下
        try {
            //获取输入流
            InputStream inputStream = fileSongMP3.getInputStream();
            //获取输出流
            //准备待写入的文件
            String url="C:\\slmmn\\song\\"+fileSongMP3.getName()+s+".mp3";
            writeFile(inputStream, url);
            //设置歌曲类歌的存放路径
            song.setSong("/song/"+fileSongMP3.getName()+s+".mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        songService.save(song);
        return Result.ok();
    }


    @ApiOperation(value = "歌曲分页")
    @GetMapping("/songPage")
    @ResponseBody
    @CrossOrigin
    public Result songPage(PageVo pageVo){
        //将歌曲实体类，遍历歌曲集合，转为vo
        //获取歌曲分页数据
        log.info("pageVo:" + pageVo);
        Page objectPage = new Page<>(pageVo.getStartIndex(),pageVo.getSize());
        Page songPage;
        if (pageVo.getStr()!=null && !pageVo.getStr().equals("")){
            log.info("存在模糊查询");
            QueryWrapper<Song> qw=new QueryWrapper<>();
            qw.like("song_name",pageVo.getStr());
            songPage = songService.page(objectPage,qw);
        }else {
            log.info("不存在模糊查询");
            songPage = songService.page(objectPage);
        }
        log.info("songPage:"+songPage);
        //将歌曲集合转化为vo
        List<Song> songRecords = songPage.getRecords();
        List<SongVo> songVOS=new ArrayList<>();
        //改造page，将comment的vo封装给commentPage
        for (Song song : songRecords){
            System.out.println(song);
            SongVo songVo = new SongVo();
            songVo.setId(song.getId());//id
            songVo.setSongImg(song.getSongImg());//图片地址
            songVo.setSongName(song.getSongName());//歌名
            songVo.setWords(song.getWords());//歌词
            songVo.setSongTime(song.getSongTime());//播放时长
            log.info("singerId:"+song.getSingerId());
            if (singerService.getById(song.getSingerId())==null){
                songVo.setSingerName("未知歌手");
            }else {
                songVo.setSingerName(singerService.getById(song.getSingerId()).getSingerName());//歌手
            }
            songVo.setHeat(song.getHeat());//热度
            songVo.setNum(song.getNum());
            songVo.setCreateTime(song.getCreateTime());
            System.out.println(songVo);
            songVOS.add(songVo);
        }
        songPage.setRecords(songVOS);
        return Result.ok(pageVo.getStr(),songPage);
    }
    @DeleteMapping("/songDel/{id}")
    @ApiOperation("删除歌曲")
    @ResponseBody
    public Result songDel(@PathVariable Integer id){
        return Result.ok(songService.removeById(id));
    }
    @ApiOperation("根据id批量删除")
    @DeleteMapping("/songDelIds")
    @ResponseBody
    public Result songDelIds(SongIdsVo ids){
        return Result.ok(songService.removeBatchByIds(ids.getIds()));
    }
    @ApiOperation("根据id查询歌曲信息")
    @GetMapping("/songQueryById/{id}")
    @ResponseBody
    public Result songQueryById(@PathVariable Integer id){
        return Result.ok(songService.getById(id));
    }

    @PostMapping("/songUpdateWords/{id}/{msg}")
    @ApiOperation("更新歌词")
    @ResponseBody
    public Result songUpdateWords(@PathVariable Integer id,@PathVariable String msg){
        int i = songService.updateSongWords(id, msg);
        return Result.ok(i);
    }




    private void writeFile(InputStream inputStream, String url) throws IOException {
        File target = new File(url);
        //获取输出流
        FileOutputStream fos = new FileOutputStream(target);
        //获取包装类
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //写文件
        int ch = 0;
        while ((ch = bis.read()) != -1) {
            bos.write(ch);
        }
        // 关流
        bos.close();
        bis.close();
    }
}
